package com.dhcc.hikari.util.thread.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import com.dhcc.hikari.util.thread.runnable.ThreadManager;
/**
 * 
* <p>标题: ThreadPoolWithcallable.java</p>
* <p>业务描述:ThreadPoolWithcallable线程池</p>
* <p>公司:东华软件股份公司</p>
* <p>版权:dhcc2013</p>
* @author 胡凯
* @date Nov 27, 2018
* @version V1.0
 */
public class ThreadPoolWithcallable {
	public static ThreadPoolByCallable instance;
	private ThreadPoolExecutor longExecutor; // 耗时比较长的线程池 用来请求网络
	private ThreadPoolExecutor shortExecutor; // 比较短的线程池 用来加载本地数据

	// 获取单例的线程池对象
	public static ThreadPoolByCallable getInstance() {
		if (instance == null) {
			System.err.println("线程池初始化--->首次进入");
			synchronized (ThreadManager.class) {
				if (instance == null) {
					int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
					int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
					instance = new ThreadPoolByCallable(threadNum);// 默认是双核的cpu 每个核心走一个线程 一个等待线程
				}
			}
		}
		return instance;
	}

	public static class ThreadPoolByCallable {
		private ExecutorService exec;
		private int corePoolSize;

		private ThreadPoolByCallable(int corePoolSize) {
			this.corePoolSize = corePoolSize;
		}

		//执行任务execute
		public  <T> Future<?> submit(Callable<?> callable) {
			if (callable == null) {
				return null;
			}
			if (exec == null) {
				exec = Executors.newFixedThreadPool(corePoolSize);
			}
			Future<?> submit = exec.submit(callable);
			return submit;
		} 
		//线程池shutdown
		public  void shutdown() {
			if (exec!=null) {
				exec.shutdown();
			}
		} 
	}
}
